package com.qhyiyun.baseweb.filter;

import com.qhyiyun.baseweb.util.CustomHttpServletRequestWrapper;
import com.qhyiyun.baseweb.util.Sm4Util;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.Security;

import static java.nio.charset.StandardCharsets.*;

@Component
public class DeParamFilter implements Filter {

    private SecretKey secretKey;

    private static final Logger logger = LoggerFactory.getLogger(DeParamFilter.class);

    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 读取请求体内容
        StringBuilder sb = new StringBuilder();
        StringBuilder filteredHexString = new StringBuilder();
        InputStream inputStream=request.getInputStream();
        //获取参数流
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(new String(line.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
            }
            //过滤非16进制字符
            for (char c : sb.toString().toCharArray()) {
                if (Character.digit(c, 16) != -1) {
                    filteredHexString.append(c);
                }
            }
        }
        if(filteredHexString.length()>0){
            logger.info("加密数据------"+filteredHexString.toString());
            byte[] detext=Hex.decode(filteredHexString.toString());
            //sm4解密
            byte[] plaintext=Sm4Util.decrypt(detext,null,null,null);
            logger.info("解密数据---------------"+new String(plaintext, UTF_8));
            String paramDeStr=new String(plaintext, UTF_8);
            // 使用自定义的 HttpServletRequestWrapper
            CustomHttpServletRequestWrapper wrappedRequest = new CustomHttpServletRequestWrapper(httpRequest, paramDeStr);
            chain.doFilter(wrappedRequest, response);
            return;
        }
        String method=((HttpServletRequest) request).getMethod();
        logger.info("请求方式----" + method);
        // 如果是预检请求（OPTIONS），直接返回响应
        if (method.equalsIgnoreCase("OPTIONS")) {
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(httpRequest, response);
    }

    @Override
    public void destroy() {
        // Clean up resources if necessary
    }
}
